package com.ftg.learn.util;


import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Redis从节点负载均衡器
 */
public class RedisFollowerLoadBalancer {

    private final List<RedisTemplate<String, Object>> followers;
    private final AtomicInteger counter = new AtomicInteger(0);

    public RedisFollowerLoadBalancer(List<RedisTemplate<String, Object>> followers) {
        this.followers = followers;
    }

    /**
     * 通过轮询方式获取Redis从节点模板
     *
     * @return RedisTemplate
     */
    public RedisTemplate<String, Object> getBalancedFollower() {
        int index = counter.getAndIncrement() % followers.size();
        // 确保索引不会为负数
        if (counter.get() < 0) {
            counter.set(0);
        }
        return followers.get(Math.abs(index));
    }

    /**
     * 获取从节点数量
     *
     * @return 从节点数量
     */
    public int getFollowerCount() {
        return followers.size();
    }
}
